* Split Mysql/Sqlite updates into their own files
[lhc/web/wiklou.git] / maintenance / updaters.inc
1 <?php
2 /**
3 * @file
4 * @ingroup Maintenance
5 */
6
7 if ( !defined( 'MEDIAWIKI' ) ) {
8 echo "This file is not a valid entry point\n";
9 exit( 1 );
10 }
11
12 require_once 'convertLinks.inc';
13 require_once 'userDupes.inc';
14 # Extension updates
15 require_once( "$IP/includes/Hooks.php" );
16
17 /**
18 * @deprecated. Do not use, ever.
19 */
20 $wgUpdates = array();
21
22
23 # For extensions only, should be populated via hooks
24 # $wgDBtype should be checked to specifiy the proper file
25 $wgExtNewTables = array(); // table, dir
26 $wgExtNewFields = array(); // table, column, dir
27 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
28 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
29 $wgExtNewIndexes = array(); // table, index, dir
30 $wgExtModifiedFields = array(); // table, index, dir
31
32 # Helper function: check if the given key is present in the updatelog table.
33 # Obviously, only use this for updates that occur after the updatelog table was
34 # created!
35 function update_row_exists( $key ) {
36 $dbr = wfGetDB( DB_SLAVE );
37 $row = $dbr->selectRow(
38 'updatelog',
39 '1',
40 array( 'ul_key' => $key ),
41 __FUNCTION__
42 );
43 return (bool)$row;
44 }
45
46 function rename_table( $from, $to, $patch ) {
47 global $wgDatabase;
48 if ( $wgDatabase->tableExists( $from ) ) {
49 if ( $wgDatabase->tableExists( $to ) ) {
50 wfOut( "...can't move table $from to $to, $to already exists.\n" );
51 } else {
52 wfOut( "Moving table $from to $to..." );
53 $wgDatabase->sourceFile( archive( $patch ) );
54 wfOut( "ok\n" );
55 }
56 } else {
57 // Source table does not exist
58 // Renames are done before creations, so this is typical for a new installation
59 // Ignore silently
60 }
61 }
62
63 function add_table( $name, $patch, $fullpath = false ) {
64 global $wgDatabase;
65 if ( $wgDatabase->tableExists( $name ) ) {
66 wfOut( "...$name table already exists.\n" );
67 } else {
68 wfOut( "Creating $name table..." );
69 if ( $fullpath ) {
70 $wgDatabase->sourceFile( $patch );
71 } else {
72 $wgDatabase->sourceFile( archive( $patch ) );
73 }
74 wfOut( "ok\n" );
75 }
76 }
77
78 function modify_field( $table, $field, $patch, $fullpath = false ) {
79 global $wgDatabase;
80 if ( !$wgDatabase->tableExists( $table ) ) {
81 wfOut( "...$table table does not exist, skipping modify field patch\n" );
82 } elseif ( ! $wgDatabase->fieldExists( $table, $field ) ) {
83 wfOut( "...$field field does not exist in $table table, skipping modify field patch\n" );
84 } else {
85 wfOut( "Modifying $field field of table $table..." );
86 if ( $fullpath ) {
87 $wgDatabase->sourceFile( $patch );
88 } else {
89 $wgDatabase->sourceFile( archive( $patch ) );
90 }
91 wfOut( "ok\n" );
92 }
93 }
94
95 function add_field( $table, $field, $patch, $fullpath = false ) {
96 global $wgDatabase;
97 if ( !$wgDatabase->tableExists( $table ) ) {
98 wfOut( "...$table table does not exist, skipping new field patch\n" );
99 } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
100 wfOut( "...have $field field in $table table.\n" );
101 } else {
102 wfOut( "Adding $field field to table $table..." );
103 if ( $fullpath ) {
104 $wgDatabase->sourceFile( $patch );
105 } else {
106 $wgDatabase->sourceFile( archive( $patch ) );
107 }
108 wfOut( "ok\n" );
109 }
110 }
111
112 function add_index( $table, $index, $patch, $fullpath = false ) {
113 global $wgDatabase;
114 if ( $wgDatabase->indexExists( $table, $index ) ) {
115 wfOut( "...$index key already set on $table table.\n" );
116 } else {
117 wfOut( "Adding $index key to table $table... " );
118 if ( $fullpath ) {
119 $wgDatabase->sourceFile( $patch );
120 } else {
121 $wgDatabase->sourceFile( archive( $patch ) );
122 }
123 wfOut( "ok\n" );
124 }
125 }
126
127 function drop_index_if_exists( $table, $index, $patch, $fullpath = false ) {
128 global $wgDatabase;
129 if ( $wgDatabase->indexExists( $table, $index ) ) {
130 wfOut( "Dropping $index from table $table... " );
131 if ( $fullpath ) {
132 $wgDatabase->sourceFile( $patch );
133 } else {
134 $wgDatabase->sourceFile( archive( $patch ) );
135 }
136 wfOut( "ok\n" );
137 } else {
138 wfOut( "...$index doesn't exist.\n" );
139 }
140 }
141
142 function do_interwiki_update() {
143 # Check that interwiki table exists; if it doesn't source it
144 global $wgDatabase, $IP;
145 if ( $wgDatabase->tableExists( "interwiki" ) ) {
146 wfOut( "...already have interwiki table\n" );
147 return true;
148 }
149 wfOut( "Creating interwiki table: " );
150 $wgDatabase->sourceFile( archive( "patch-interwiki.sql" ) );
151 wfOut( "ok\n" );
152 wfOut( "Adding default interwiki definitions: " );
153 $wgDatabase->sourceFile( "$IP/maintenance/interwiki.sql" );
154 wfOut( "ok\n" );
155 }
156
157 function do_index_update() {
158 # Check that proper indexes are in place
159 global $wgDatabase;
160 $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
161 if ( !$meta->isMultipleKey() ) {
162 wfOut( "Updating indexes to 20031107: " );
163 $wgDatabase->sourceFile( archive( "patch-indexes.sql" ) );
164 wfOut( "ok\n" );
165 return true;
166 }
167 wfOut( "...indexes seem up to 20031107 standards\n" );
168 return false;
169 }
170
171 function do_image_index_update() {
172 global $wgDatabase;
173
174 $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
175 if ( !$meta->isMultipleKey() ) {
176 wfOut( "Updating indexes to 20050912: " );
177 $wgDatabase->sourceFile( archive( "patch-mimesearch-indexes.sql" ) );
178 wfOut( "ok\n" );
179 return true;
180 }
181 wfOut( "...indexes seem up to 20050912 standards\n" );
182 return false;
183 }
184
185 function do_image_name_unique_update() {
186 global $wgDatabase;
187 if ( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
188 wfOut( "...image primary key already set.\n" );
189 } else {
190 wfOut( "Making img_name the primary key... " );
191 $wgDatabase->sourceFile( archive( "patch-image_name_primary.sql" ) );
192 wfOut( "ok\n" );
193 }
194 }
195
196 function do_logging_timestamp_index() {
197 global $wgDatabase;
198 if ( $wgDatabase->indexExists( 'logging', 'times' ) ) {
199 wfOut( "...timestamp key on logging already exists.\n" );
200 } else {
201 wfOut( "Adding timestamp key on logging table... " );
202 $wgDatabase->sourceFile( archive( "patch-logging-times-index.sql" ) );
203 wfOut( "ok\n" );
204 }
205 }
206
207 function do_archive_user_index() {
208 global $wgDatabase;
209 if ( $wgDatabase->indexExists( 'archive', 'usertext_timestamp' ) ) {
210 wfOut( "...usertext,timestamp key on archive already exists.\n" );
211 } else {
212 wfOut( "Adding usertext,timestamp key on archive table... " );
213 $wgDatabase->sourceFile( archive( "patch-archive-user-index.sql" ) );
214 wfOut( "ok\n" );
215 }
216 }
217
218 function do_image_user_index() {
219 global $wgDatabase;
220 if ( $wgDatabase->indexExists( 'image', 'img_usertext_timestamp' ) ) {
221 wfOut( "...usertext,timestamp key on image already exists.\n" );
222 } else {
223 wfOut( "Adding usertext,timestamp key on image table... " );
224 $wgDatabase->sourceFile( archive( "patch-image-user-index.sql" ) );
225 wfOut( "ok\n" );
226 }
227 }
228
229 function do_oldimage_user_index() {
230 global $wgDatabase;
231 if ( $wgDatabase->indexExists( 'oldimage', 'oi_usertext_timestamp' ) ) {
232 wfOut( "...usertext,timestamp key on oldimage already exists.\n" );
233 } else {
234 wfOut( "Adding usertext,timestamp key on oldimage table... " );
235 $wgDatabase->sourceFile( archive( "patch-oldimage-user-index.sql" ) );
236 wfOut( "ok\n" );
237 }
238 }
239
240 function do_watchlist_update() {
241 global $wgDatabase;
242 $fname = 'do_watchlist_update';
243 if ( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
244 wfOut( "...the watchlist table is already set up for email notification.\n" );
245 } else {
246 wfOut( "Adding wl_notificationtimestamp field for email notification management." );
247 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
248 $wgDatabase->sourceFile( archive( 'patch-email-notification.sql' ) );
249 wfOut( "ok\n" );
250 }
251 # Check if we need to add talk page rows to the watchlist
252 $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
253 $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
254 if ( $talk != $nontalk ) {
255 wfOut( "Adding missing watchlist talk page rows... " );
256 flush();
257
258 $wgDatabase->insertSelect( 'watchlist', 'watchlist',
259 array(
260 'wl_user' => 'wl_user',
261 'wl_namespace' => 'wl_namespace | 1',
262 'wl_title' => 'wl_title',
263 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
264 ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
265 wfOut( "ok\n" );
266 } else {
267 wfOut( "...watchlist talk page rows already present\n" );
268 }
269 }
270
271 function do_copy_newtalk_to_watchlist() {
272 global $wgDatabase;
273 global $wgCommandLineMode; # this needs to be saved while getID() and getName() are called
274
275 $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
276 $wgDatabase->tableName( 'user_newtalk' ) );
277 $num_newtalks = $wgDatabase->numRows( $res );
278 wfOut( "Now converting $num_newtalks user_newtalk entries to watchlist table entries ... \n" );
279
280 $user = new User();
281 for ( $i = 1; $i <= $num_newtalks; $i++ ) {
282 $wluser = $wgDatabase->fetchObject( $res );
283 if ( $wluser->user_id == 0 ) { # anonymous users ... have IP numbers as "names"
284 if ( $user->isIP( $wluser->user_ip ) ) { # do only if it really looks like an IP number (double checked)
285 $wgDatabase->replace( 'watchlist',
286 array( array( 'wl_user', 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ) ),
287 array( 'wl_user' => 0,
288 'wl_namespace' => NS_USER_TALK,
289 'wl_title' => $wluser->user_ip,
290 'wl_notificationtimestamp' => '19700101000000'
291 ), 'updaters.inc::do_watchlist_update2'
292 );
293 }
294 } else { # normal users ... have user_ids
295 $user->setID( $wluser->user_id );
296 $wgDatabase->replace( 'watchlist',
297 array( array( 'wl_user', 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ) ),
298 array( 'wl_user' => $user->getID(),
299 'wl_namespace' => NS_USER_TALK,
300 'wl_title' => $user->getName(),
301 'wl_notificationtimestamp' => '19700101000000'
302 ), 'updaters.inc::do_watchlist_update3'
303 );
304 }
305 }
306 wfOut( "Done.\n" );
307 }
308
309 function do_user_update() {
310 global $wgDatabase;
311 if ( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
312 wfOut( "User table contains old email authentication field. Dropping... " );
313 $wgDatabase->sourceFile( archive( 'patch-email-authentication.sql' ) );
314 wfOut( "ok\n" );
315 } else {
316 wfOut( "...user table does not contain old email authentication field.\n" );
317 }
318 }
319
320 /**
321 * 1.4 betas were missing the 'binary' marker from logging.log_title,
322 * which causes a collation mismatch error on joins in MySQL 4.1.
323 */
324 function check_bin( $table, $field, $patchFile ) {
325 global $wgDatabase, $wgDBtype;
326 if ( $wgDBtype != 'mysql' )
327 return;
328 $tableName = $wgDatabase->tableName( $table );
329 $res = $wgDatabase->query( "SELECT $field FROM $tableName LIMIT 0" );
330 $flags = explode( ' ', mysql_field_flags( $res->result, 0 ) );
331 $wgDatabase->freeResult( $res );
332
333 if ( in_array( 'binary', $flags ) ) {
334 wfOut( "...$table table has correct $field encoding.\n" );
335 } else {
336 wfOut( "Fixing $field encoding on $table table... " );
337 $wgDatabase->sourceFile( archive( $patchFile ) );
338 wfOut( "ok\n" );
339 }
340 }
341
342 function do_schema_restructuring() {
343 global $wgDatabase;
344 $fname = "do_schema_restructuring";
345 if ( $wgDatabase->tableExists( 'page' ) ) {
346 wfOut( "...page table already exists.\n" );
347 } else {
348 wfOut( "...converting from cur/old to page/revision/text DB structure.\n" );
349 wfOut( wfTimestamp( TS_DB ) );
350 wfOut( "......checking for duplicate entries.\n" );
351
352 list ( $cur, $old, $page, $revision, $text ) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
353
354 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
355 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
356
357 if ( $wgDatabase->numRows( $rows ) > 0 ) {
358 wfOut( wfTimestamp( TS_DB ) );
359 wfOut( "......<b>Found duplicate entries</b>\n" );
360 wfOut( sprintf( "<b> %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
361 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
362 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
363 $duplicate[$row->cur_namespace] = array();
364 }
365 $duplicate[$row->cur_namespace][] = $row->cur_title;
366 wfOut( sprintf( " %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
367 }
368 $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
369 $firstCond = true;
370 foreach ( $duplicate as $ns => $titles ) {
371 if ( $firstCond ) {
372 $firstCond = false;
373 } else {
374 $sql .= ' OR ';
375 }
376 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
377 $first = true;
378 foreach ( $titles as $t ) {
379 if ( $first ) {
380 $sql .= $wgDatabase->addQuotes( $t );
381 $first = false;
382 } else {
383 $sql .= ', ' . $wgDatabase->addQuotes( $t );
384 }
385 }
386 $sql .= ") ) \n";
387 }
388 # By sorting descending, the most recent entry will be the first in the list.
389 # All following entries will be deleted by the next while-loop.
390 $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
391
392 $rows = $wgDatabase->query( $sql, $fname );
393
394 $prev_title = $prev_namespace = false;
395 $deleteId = array();
396
397 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
398 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
399 $deleteId[] = $row->cur_id;
400 }
401 $prev_title = $row->cur_title;
402 $prev_namespace = $row->cur_namespace;
403 }
404 $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
405 $rows = $wgDatabase->query( $sql, $fname );
406 wfOut( wfTimestamp( TS_DB ) );
407 wfOut( "......<b>Deleted</b> " . $wgDatabase->affectedRows() . " records.\n" );
408 }
409
410
411 wfOut( wfTimestamp( TS_DB ) );
412 wfOut( "......Creating tables.\n" );
413 $wgDatabase->query( "CREATE TABLE $page (
414 page_id int(8) unsigned NOT NULL auto_increment,
415 page_namespace int NOT NULL,
416 page_title varchar(255) binary NOT NULL,
417 page_restrictions tinyblob NOT NULL,
418 page_counter bigint(20) unsigned NOT NULL default '0',
419 page_is_redirect tinyint(1) unsigned NOT NULL default '0',
420 page_is_new tinyint(1) unsigned NOT NULL default '0',
421 page_random real unsigned NOT NULL,
422 page_touched char(14) binary NOT NULL default '',
423 page_latest int(8) unsigned NOT NULL,
424 page_len int(8) unsigned NOT NULL,
425
426 PRIMARY KEY page_id (page_id),
427 UNIQUE INDEX name_title (page_namespace,page_title),
428 INDEX (page_random),
429 INDEX (page_len)
430 ) ENGINE=InnoDB", $fname );
431 $wgDatabase->query( "CREATE TABLE $revision (
432 rev_id int(8) unsigned NOT NULL auto_increment,
433 rev_page int(8) unsigned NOT NULL,
434 rev_comment tinyblob NOT NULL,
435 rev_user int(5) unsigned NOT NULL default '0',
436 rev_user_text varchar(255) binary NOT NULL default '',
437 rev_timestamp char(14) binary NOT NULL default '',
438 rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
439 rev_deleted tinyint(1) unsigned NOT NULL default '0',
440 rev_len int(8) unsigned,
441 rev_parent_id int(8) unsigned default NULL,
442 PRIMARY KEY rev_page_id (rev_page, rev_id),
443 UNIQUE INDEX rev_id (rev_id),
444 INDEX rev_timestamp (rev_timestamp),
445 INDEX page_timestamp (rev_page,rev_timestamp),
446 INDEX user_timestamp (rev_user,rev_timestamp),
447 INDEX usertext_timestamp (rev_user_text,rev_timestamp)
448 ) ENGINE=InnoDB", $fname );
449
450 wfOut( wfTimestamp( TS_DB ) );
451 wfOut( "......Locking tables.\n" );
452 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
453
454 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
455 wfOut( wfTimestamp( TS_DB ) );
456 wfOut( "......maxold is {$maxold}\n" );
457
458 wfOut( wfTimestamp( TS_DB ) );
459 global $wgLegacySchemaConversion;
460 if ( $wgLegacySchemaConversion ) {
461 // Create HistoryBlobCurStub entries.
462 // Text will be pulled from the leftover 'cur' table at runtime.
463 wfOut( "......Moving metadata from cur; using blob references to text in cur table.\n" );
464 $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
465 $cur_flags = "'object'";
466 } else {
467 // Copy all cur text in immediately: this may take longer but avoids
468 // having to keep an extra table around.
469 wfOut( "......Moving text from cur.\n" );
470 $cur_text = 'cur_text';
471 $cur_flags = "''";
472 }
473 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
474 old_timestamp, old_minor_edit, old_flags)
475 SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
476 FROM $cur", $fname );
477
478 wfOut( wfTimestamp( TS_DB ) );
479 wfOut( "......Setting up revision table.\n" );
480 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
481 rev_minor_edit)
482 SELECT old_id, cur_id, old_comment, old_user, old_user_text,
483 old_timestamp, old_minor_edit
484 FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
485
486 wfOut( wfTimestamp( TS_DB ) );
487 wfOut( "......Setting up page table.\n" );
488 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
489 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
490 SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
491 cur_random, cur_touched, rev_id, LENGTH(cur_text)
492 FROM $cur,$revision
493 WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
494
495 wfOut( wfTimestamp( TS_DB ) );
496 wfOut( "......Unlocking tables.\n" );
497 $wgDatabase->query( "UNLOCK TABLES", $fname );
498
499 wfOut( wfTimestamp( TS_DB ) );
500 wfOut( "......Renaming old.\n" );
501 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
502
503 wfOut( wfTimestamp( TS_DB ) );
504 wfOut( "...done.\n" );
505 }
506 }
507
508 function do_inverse_timestamp() {
509 global $wgDatabase;
510 if ( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
511 wfOut( "Removing revision.inverse_timestamp and fixing indexes... " );
512 $wgDatabase->sourceFile( archive( 'patch-inverse_timestamp.sql' ) );
513 wfOut( "ok\n" );
514 } else {
515 wfOut( "...revision timestamp indexes already up to 2005-03-13\n" );
516 }
517 }
518
519 function do_text_id() {
520 global $wgDatabase;
521 if ( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
522 wfOut( "...rev_text_id already in place.\n" );
523 } else {
524 wfOut( "Adding rev_text_id field... " );
525 $wgDatabase->sourceFile( archive( 'patch-rev_text_id.sql' ) );
526 wfOut( "ok\n" );
527 }
528 }
529
530 function do_namespace_size() {
531 $tables = array(
532 'page' => 'page',
533 'archive' => 'ar',
534 'recentchanges' => 'rc',
535 'watchlist' => 'wl',
536 'querycache' => 'qc',
537 'logging' => 'log',
538 );
539 foreach ( $tables as $table => $prefix ) {
540 do_namespace_size_on( $table, $prefix );
541 flush();
542 }
543 }
544
545 function do_namespace_size_on( $table, $prefix ) {
546 global $wgDatabase, $wgDBtype;
547 if ( $wgDBtype != 'mysql' )
548 return;
549 $field = $prefix . '_namespace';
550
551 $tablename = $wgDatabase->tableName( $table );
552 $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
553 $info = $wgDatabase->fetchObject( $result );
554 $wgDatabase->freeResult( $result );
555
556 if ( substr( $info->Type, 0, 3 ) == 'int' ) {
557 wfOut( "...$field is already a full int ($info->Type).\n" );
558 } else {
559 wfOut( "Promoting $field from $info->Type to int... " );
560
561 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
562 $wgDatabase->query( $sql );
563
564 wfOut( "ok\n" );
565 }
566 }
567
568 function do_pagelinks_update() {
569 global $wgDatabase;
570 if ( $wgDatabase->tableExists( 'pagelinks' ) ) {
571 wfOut( "...already have pagelinks table.\n" );
572 } else {
573 wfOut( "Converting links and brokenlinks tables to pagelinks... " );
574 $wgDatabase->sourceFile( archive( 'patch-pagelinks.sql' ) );
575 wfOut( "ok\n" );
576 flush();
577
578 global $wgCanonicalNamespaceNames;
579 foreach ( $wgCanonicalNamespaceNames as $ns => $name ) {
580 if ( $ns != 0 ) {
581 do_pagelinks_namespace( $ns );
582 }
583 }
584 }
585 }
586
587 function do_pagelinks_namespace( $namespace ) {
588 global $wgDatabase, $wgContLang;
589
590 $ns = intval( $namespace );
591 wfOut( "Cleaning up broken links for namespace $ns... " );
592
593 $pagelinks = $wgDatabase->tableName( 'pagelinks' );
594 $name = $wgContLang->getNsText( $ns );
595 $prefix = $wgDatabase->strencode( $name );
596 $likeprefix = str_replace( '_', '\\_', $prefix );
597
598 $sql = "UPDATE $pagelinks
599 SET pl_namespace=$ns,
600 pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
601 WHERE pl_namespace=0
602 AND pl_title LIKE '$likeprefix:%'";
603
604 $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
605 wfOut( "ok\n" );
606 }
607
608 function do_drop_img_type() {
609 global $wgDatabase;
610
611 if ( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
612 wfOut( "Dropping unused img_type field in image table... " );
613 $wgDatabase->sourceFile( archive( 'patch-drop_img_type.sql' ) );
614 wfOut( "ok\n" );
615 } else {
616 wfOut( "...no img_type field in image table; Good.\n" );
617 }
618 }
619
620 function do_old_links_update() {
621 global $wgDatabase;
622 if ( $wgDatabase->tableExists( 'pagelinks' ) ) {
623 wfOut( "...have pagelinks; skipping old links table updates.\n" );
624 } else {
625 convertLinks(); flush();
626 }
627 }
628
629 function fix_ancient_imagelinks() {
630 global $wgDatabase;
631 $info = $wgDatabase->fieldInfo( 'imagelinks', 'il_from' );
632 if ( $info && $info->type() === 'string' ) {
633 wfOut( "Fixing ancient broken imagelinks table.\n" );
634 wfOut( "NOTE: you will have to run maintenance/refreshLinks.php after this.\n" );
635 $wgDatabase->sourceFile( archive( 'patch-fix-il_from.sql' ) );
636 wfOut( "ok\n" );
637 } else {
638 wfOut( "...il_from OK\n" );
639 }
640 }
641
642 function do_user_unique_update() {
643 global $wgDatabase;
644 $duper = new UserDupes( $wgDatabase );
645 if ( $duper->hasUniqueIndex() ) {
646 wfOut( "...already have unique user_name index.\n" );
647 } else {
648 if ( !$duper->clearDupes() ) {
649 wfOut( "WARNING: This next step will probably fail due to unfixed duplicates...\n" );
650 }
651 wfOut( "Adding unique index on user_name... " );
652 $wgDatabase->sourceFile( archive( 'patch-user_nameindex.sql' ) );
653 wfOut( "ok\n" );
654 }
655 }
656
657 function do_user_groups_update() {
658 $fname = 'do_user_groups_update';
659 global $wgDatabase;
660
661 if ( $wgDatabase->tableExists( 'user_groups' ) ) {
662 wfOut( "...user_groups table already exists.\n" );
663 return do_user_groups_reformat();
664 }
665
666 wfOut( "Adding user_groups table... " );
667 $wgDatabase->sourceFile( archive( 'patch-user_groups.sql' ) );
668 wfOut( "ok\n" );
669
670 if ( !$wgDatabase->tableExists( 'user_rights' ) ) {
671 if ( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
672 wfOut( "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion..." );
673 $wgDatabase->sourceFile( archive( 'patch-user_rights.sql' ) );
674 wfOut( "ok\n" );
675 } else {
676 wfOut( "*** WARNING: couldn't locate user_rights table or field for upgrade.\n" );
677 wfOut( "*** You may need to manually configure some sysops by manipulating\n" );
678 wfOut( "*** the user_groups table.\n" );
679 return;
680 }
681 }
682
683 wfOut( "Converting user_rights table to user_groups... " );
684 $result = $wgDatabase->select( 'user_rights',
685 array( 'ur_user', 'ur_rights' ),
686 array( "ur_rights != ''" ),
687 $fname );
688
689 while ( $row = $wgDatabase->fetchObject( $result ) ) {
690 $groups = array_unique(
691 array_map( 'trim',
692 explode( ',', $row->ur_rights ) ) );
693
694 foreach ( $groups as $group ) {
695 $wgDatabase->insert( 'user_groups',
696 array(
697 'ug_user' => $row->ur_user,
698 'ug_group' => $group ),
699 $fname );
700 }
701 }
702 $wgDatabase->freeResult( $result );
703 wfOut( "ok\n" );
704 }
705
706 function do_user_groups_reformat() {
707 # Check for bogus formats from previous 1.5 alpha code.
708 global $wgDatabase;
709 $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
710
711 if ( $info->type() == 'int' ) {
712 $oldug = $wgDatabase->tableName( 'user_groups' );
713 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
714 wfOut( "user_groups is in bogus intermediate format. Renaming to $newug... " );
715 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
716 wfOut( "ok\n" );
717
718 wfOut( "Re-adding fresh user_groups table... " );
719 $wgDatabase->sourceFile( archive( 'patch-user_groups.sql' ) );
720 wfOut( "ok\n" );
721
722 wfOut( "***\n" );
723 wfOut( "*** WARNING: You will need to manually fix up user permissions in the user_groups\n" );
724 wfOut( "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n" );
725 wfOut( "***\n" );
726 } else {
727 wfOut( "...user_groups is in current format.\n" );
728 }
729
730 }
731
732 function do_watchlist_null() {
733 # Make sure wl_notificationtimestamp can be NULL,
734 # and update old broken items.
735 global $wgDatabase;
736 $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
737
738 if ( !$info->nullable() ) {
739 wfOut( "Making wl_notificationtimestamp nullable... " );
740 $wgDatabase->sourceFile( archive( 'patch-watchlist-null.sql' ) );
741 wfOut( "ok\n" );
742 } else {
743 wfOut( "...wl_notificationtimestamp is already nullable.\n" );
744 }
745
746 }
747
748 /**
749 * @bug 3946
750 */
751 function do_page_random_update() {
752 global $wgDatabase;
753
754 wfOut( "Setting page_random to a random value on rows where it equals 0..." );
755
756 $page = $wgDatabase->tableName( 'page' );
757 $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
758 $rows = $wgDatabase->affectedRows();
759
760 wfOut( "changed $rows rows\n" );
761 }
762
763 function do_templatelinks_update() {
764 global $wgDatabase, $wgLoadBalancer;
765 $fname = 'do_templatelinks_update';
766
767 if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
768 wfOut( "...templatelinks table already exists\n" );
769 return;
770 }
771 wfOut( "Creating templatelinks table...\n" );
772 $wgDatabase->sourceFile( archive( 'patch-templatelinks.sql' ) );
773 wfOut( "Populating...\n" );
774 if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
775 // Slow, replication-friendly update
776 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
777 array( 'pl_namespace' => NS_TEMPLATE ), $fname );
778 $count = 0;
779 while ( $row = $wgDatabase->fetchObject( $res ) ) {
780 $count = ( $count + 1 ) % 100;
781 if ( $count == 0 ) {
782 if ( function_exists( 'wfWaitForSlaves' ) ) {
783 wfWaitForSlaves( 10 );
784 } else {
785 sleep( 1 );
786 }
787 }
788 $wgDatabase->insert( 'templatelinks',
789 array(
790 'tl_from' => $row->pl_from,
791 'tl_namespace' => $row->pl_namespace,
792 'tl_title' => $row->pl_title,
793 ), $fname
794 );
795
796 }
797 $wgDatabase->freeResult( $res );
798 } else {
799 // Fast update
800 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
801 array(
802 'tl_from' => 'pl_from',
803 'tl_namespace' => 'pl_namespace',
804 'tl_title' => 'pl_title'
805 ), array(
806 'pl_namespace' => 10
807 ), $fname
808 );
809 }
810 wfOut( "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n" );
811 }
812
813 // Add index on ( rc_namespace, rc_user_text ) [Jul. 2006]
814 // Add index on ( rc_user_text, rc_timestamp ) [Nov. 2006]
815 function do_rc_indices_update() {
816 global $wgDatabase;
817 wfOut( "Checking for additional recent changes indices...\n" );
818
819 $indexes = array(
820 'rc_ns_usertext' => 'patch-recentchanges-utindex.sql',
821 'rc_user_text' => 'patch-rc_user_text-index.sql',
822 );
823
824 foreach ( $indexes as $index => $patch ) {
825 $info = $wgDatabase->indexInfo( 'recentchanges', $index, __METHOD__ );
826 if ( !$info ) {
827 wfOut( "...index `{$index}` not found; adding..." );
828 $wgDatabase->sourceFile( archive( $patch ) );
829 wfOut( "done.\n" );
830 } else {
831 wfOut( "...index `{$index}` seems ok.\n" );
832 }
833 }
834 }
835
836 function index_has_field( $table, $index, $field ) {
837 global $wgDatabase;
838 wfOut( "Checking if $table index $index includes field $field...\n" );
839 $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
840 if ( $info ) {
841 foreach ( $info as $row ) {
842 if ( $row->Column_name == $field ) {
843 wfOut( "...index $index on table $table seems to be ok\n" );
844 return true;
845 }
846 }
847 }
848 wfOut( "...index $index on table $table has no field $field; adding\n" );
849 return false;
850 }
851
852 function do_backlinking_indices_update() {
853 global $wgDatabase;
854 wfOut( "Checking for backlinking indices...\n" );
855 if ( !index_has_field( 'pagelinks', 'pl_namespace', 'pl_from' ) ||
856 !index_has_field( 'templatelinks', 'tl_namespace', 'tl_from' ) ||
857 !index_has_field( 'imagelinks', 'il_to', 'il_from' ) )
858 {
859 $wgDatabase->sourceFile( archive( 'patch-backlinkindexes.sql' ) );
860 wfOut( "...backlinking indices updated\n" );
861 }
862 }
863
864 function do_categorylinks_indices_update() {
865 global $wgDatabase;
866 wfOut( "Checking for categorylinks indices...\n" );
867 if ( !index_has_field( 'categorylinks', 'cl_sortkey', 'cl_from' ) )
868 {
869 $wgDatabase->sourceFile( archive( 'patch-categorylinksindex.sql' ) );
870 wfOut( "...categorylinks indices updated\n" );
871 }
872 }
873
874 function do_filearchive_indices_update() {
875 global $wgDatabase;
876 wfOut( "Checking filearchive indices...\n" );
877 $info = $wgDatabase->indexInfo( 'filearchive', 'fa_user_timestamp', __METHOD__ );
878 if ( !$info )
879 {
880 $wgDatabase->sourceFile( archive( 'patch-filearchive-user-index.sql' ) );
881 wfOut( "...filearchive indices updated\n" );
882 }
883 }
884
885 function maybe_do_profiling_memory_update() {
886 global $wgDatabase;
887 if ( !$wgDatabase->tableExists( 'profiling' ) ) {
888 // Simply ignore
889 } elseif ( $wgDatabase->fieldExists( 'profiling', 'pf_memory' ) ) {
890 wfOut( "...profiling table has pf_memory field.\n" );
891 } else {
892 wfOut( "Adding pf_memory field to table profiling..." );
893 $wgDatabase->sourceFile( archive( 'patch-profiling-memory.sql' ) );
894 wfOut( "ok\n" );
895 }
896 }
897
898 function do_stats_init() {
899 // Sometimes site_stats table is not properly populated.
900 global $wgDatabase;
901 wfOut( "Checking site_stats row..." );
902 $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
903 if ( $row === false ) {
904 wfOut( "data is missing! rebuilding...\n" );
905 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
906 wfOut( "missing ss_total_pages, rebuilding...\n" );
907 } else {
908 wfOut( "ok.\n" );
909 return;
910 }
911 SiteStatsInit::doAllAndCommit( false );
912 }
913
914 function do_active_users_init() {
915 global $wgDatabase;
916 $activeUsers = $wgDatabase->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
917 if ( $activeUsers == -1 ) {
918 $activeUsers = $wgDatabase->selectField( 'recentchanges',
919 'COUNT( DISTINCT rc_user_text )',
920 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
921 );
922 $wgDatabase->update( 'site_stats',
923 array( 'ss_active_users' => intval( $activeUsers ) ),
924 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
925 );
926 }
927 wfOut( "...ss_active_users user count set...\n" );
928 }
929
930 function purge_cache() {
931 global $wgDatabase;
932 # We can't guarantee that the user will be able to use TRUNCATE,
933 # but we know that DELETE is available to us
934 wfOut( "Purging caches..." );
935 $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
936 wfOut( "done.\n" );
937 }
938
939 function do_all_updates( $shared = false, $purge = true ) {
940 global $wgNewTables, $wgExtModifiedFields, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgSharedTables, $wgDatabase, $wgDBtype, $IP;
941
942 wfRunHooks( 'LoadExtensionSchemaUpdates' );
943
944 $doUser = $shared ? $wgSharedDB && in_array( 'user', $wgSharedTables ) : !$wgSharedDB || !in_array( 'user', $wgSharedTables );
945
946 if ( $wgDBtype === 'postgres' ) {
947 do_postgres_updates();
948 return;
949 }
950
951 global $wgDatabase;
952 $up = DatabaseUpdater::newForDb( $wgDatabase );
953 $up->doUpdates();
954
955 wfOut( "Deleting old default messages (this may take a long time!)..." );
956 if ( !defined( 'MW_NO_SETUP' ) ) {
957 define( 'MW_NO_SETUP', true );
958 }
959 require_once 'deleteDefaultMessages.php';
960 DeleteDefaultMessages::reallyExecute();
961 wfOut( "Done\n" );
962
963 do_stats_init();
964
965 if ( $purge ) {
966 purge_cache();
967 }
968 }
969
970 function archive( $name ) {
971 global $wgDBtype, $IP;
972 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$name" ) ) {
973 return "$IP/maintenance/$wgDBtype/archives/$name";
974 } else {
975 return "$IP/maintenance/archives/$name";
976 }
977 }
978
979 function do_restrictions_update() {
980 # Adding page_restrictions table, obsoleting page.page_restrictions.
981 # Migrating old restrictions to new table
982 # -- Andrew Garrett, January 2007.
983
984 global $wgDatabase;
985
986 $name = 'page_restrictions';
987 $patch = 'patch-page_restrictions.sql';
988 $patch2 = 'patch-page_restrictions_sortkey.sql';
989
990 if ( $wgDatabase->tableExists( $name ) ) {
991 wfOut( "...$name table already exists.\n" );
992 } else {
993 wfOut( "Creating $name table..." );
994 $wgDatabase->sourceFile( archive( $patch ) );
995 $wgDatabase->sourceFile( archive( $patch2 ) );
996 wfOut( "ok\n" );
997
998 wfOut( "Migrating old restrictions to new table..." );
999
1000 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array( "page_restrictions!=''", "page_restrictions!='edit=:move='" ), __METHOD__ );
1001
1002 $count = 0;
1003
1004 while ( $row = $wgDatabase->fetchObject( $res ) ) {
1005 $count = ( $count + 1 ) % 100;
1006
1007 if ( $count == 0 ) {
1008 if ( function_exists( 'wfWaitForSlaves' ) ) {
1009 wfWaitForSlaves( 10 );
1010 } else {
1011 sleep( 1 );
1012 }
1013 }
1014
1015 # Figure out what the restrictions are..
1016 $id = $row->page_id;
1017 $flatrestrictions = explode( ':', $row->page_restrictions );
1018
1019 $restrictions = array ();
1020 foreach ( $flatrestrictions as $restriction ) {
1021 $thisrestriction = explode( '=', $restriction, 2 );
1022 if ( count( $thisrestriction ) == 1 ) {
1023 // Compatibility with old protections from before
1024 // separate move protection was added.
1025 list( $level ) = $thisrestriction;
1026 if ( $level ) {
1027 $restrictions['edit'] = $level;
1028 $restrictions['move'] = $level;
1029 }
1030 } else {
1031 list( $type, $level ) = $thisrestriction;
1032 if ( $level ) {
1033 $restrictions[$type] = $level;
1034 }
1035 }
1036
1037 $wgDatabase->update( 'page', array ( 'page_restrictions' => '' ), array( 'page_id' => $id ), __METHOD__ );
1038
1039 }
1040
1041 foreach ( $restrictions as $type => $level ) {
1042 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1043 'pr_type' => $type,
1044 'pr_level' => $level,
1045 'pr_cascade' => 0,
1046 'pr_expiry' => 'infinity' ),
1047 __METHOD__ );
1048 }
1049 }
1050 wfOut( "ok\n" );
1051 }
1052 }
1053
1054 function do_category_population() {
1055 if ( update_row_exists( 'populate category' ) ) {
1056 wfOut( "...category table already populated.\n" );
1057 return;
1058 }
1059 require_once( 'populateCategory.php' );
1060 wfOut(
1061 "Populating category table, printing progress markers. " .
1062 "For large databases, you\n" .
1063 "may want to hit Ctrl-C and do this manually with maintenance/\n" .
1064 "populateCategory.php.\n"
1065 );
1066 $task = new PopulateCategory();
1067 $task->execute();
1068 wfOut( "Done populating category table.\n" );
1069 }
1070
1071 function do_populate_parent_id() {
1072 if ( update_row_exists( 'populate rev_parent_id' ) ) {
1073 wfOut( "...rev_parent_id column already populated.\n" );
1074 return;
1075 }
1076 require_once( 'populateParentId.php' );
1077 $task = new PopulateParentId();
1078 $task->execute();
1079 }
1080
1081 function do_populate_rev_len() {
1082 if ( update_row_exists( 'populate rev_len' ) ) {
1083 wfOut( "...rev_len column already populated.\n" );
1084 return;
1085 }
1086 require_once( 'populateRevisionLength.php' );
1087 $task = new PopulateRevisionLength();
1088 $task->execute();
1089 }
1090
1091 function sqlite_initial_indexes() {
1092 global $wgDatabase;
1093 // initial-indexes.sql fails if the indexes are already present, so we perform a quick check if our database is newer.
1094 if ( update_row_exists( 'initial_indexes' ) || $wgDatabase->indexExists( 'user', 'user_name' ) ) {
1095 wfOut( "...have initial indexes\n" );
1096 return;
1097 }
1098 wfOut( "Adding initial indexes..." );
1099 $wgDatabase->sourceFile( archive( 'initial-indexes.sql' ) );
1100 wfOut( "done\n" );
1101 }
1102
1103 function sqlite_setup_searchindex() {
1104 global $wgDatabase;
1105 $module = $wgDatabase->getFulltextSearchModule();
1106 $fts3tTable = update_row_exists( 'fts3' );
1107 if ( $fts3tTable && !$module ) {
1108 wfOut( '...PHP is missing FTS3 support, downgrading tables...' );
1109 $wgDatabase->sourceFile( archive( 'searchindex-no-fts.sql' ) );
1110 wfOut( "done\n" );
1111 } elseif ( !$fts3tTable && $module == 'FTS3' ) {
1112 wfOut( '...adding FTS3 search capabilities...' );
1113 $wgDatabase->sourceFile( archive( 'searchindex-fts3.sql' ) );
1114 wfOut( "done\n" );
1115 } else {
1116 wfOut( "...fulltext search table appears to be in order.\n" );
1117 }
1118 }
1119
1120 function do_unique_pl_tl_il() {
1121 global $wgDatabase;
1122 $info = $wgDatabase->indexInfo( 'pagelinks', 'pl_namespace' );
1123 if ( is_array( $info ) && !$info[0]->Non_unique ) {
1124 wfOut( "...pl_namespace, tl_namespace, il_to indices are already UNIQUE.\n" );
1125 } else {
1126 wfOut( "Making pl_namespace, tl_namespace and il_to indices UNIQUE... " );
1127 $wgDatabase->sourceFile( archive( 'patch-pl-tl-il-unique.sql' ) );
1128 wfOut( "ok\n" );
1129 }
1130 }
1131
1132 function do_log_search_population() {
1133 global $wgDatabase;
1134 if ( update_row_exists( 'populate log_search' ) ) {
1135 wfOut( "...log_search table already populated.\n" );
1136 return;
1137 }
1138 require_once( 'populateLogSearch.php' );
1139 wfOut(
1140 "Populating log_search table, printing progress markers. For large\n" .
1141 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1142 "maintenance/populateLogSearch.php.\n" );
1143 $task = new PopulateLogSearch();
1144 $task->execute();
1145 wfOut( "Done populating log_search table.\n" );
1146 }
1147
1148 function rename_eu_wiki_id() {
1149 global $wgDatabase;
1150 if ( $wgDatabase->fieldExists( 'external_user', 'eu_local_id' ) ) {
1151 wfOut( "...eu_wiki_id already renamed to eu_local_id.\n" );
1152 return;
1153 }
1154 wfOut( "Renaming eu_wiki_id -> eu_local_id... " );
1155 $wgDatabase->sourceFile( archive( 'patch-eu_local_id.sql' ) );
1156 wfOut( "ok\n" );
1157 }
1158
1159 function do_update_transcache_field() {
1160 global $wgDatabase;
1161 if ( update_row_exists( 'convert transcache field' ) ) {
1162 wfOut( "...transcache tc_time already converted.\n" );
1163 return;
1164 } else {
1165 wfOut( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
1166 $wgDatabase->sourceFile( archive( 'patch-tc-timestamp.sql' ) );
1167 wfOut( "ok\n" );
1168 }
1169 }
1170
1171 function do_update_mime_minor_field() {
1172 if ( update_row_exists( 'mime_minor_length' ) ) {
1173 wfOut( "...*_mime_minor fields are already long enough.\n" );
1174 } else {
1175 global $wgDatabase;
1176 wfOut( "Altering all *_mime_minor fields to 100 bytes in size ... " );
1177 $wgDatabase->sourceFile( archive( 'patch-mime_minor_length.sql' ) );
1178 wfOut( "ok\n" );
1179 }
1180 }
1181
1182 /***********************************************************************
1183 * Start PG stuff
1184 * TODO: merge with above
1185 ***********************************************************************/
1186
1187 function pg_describe_table( $table ) {
1188 global $wgDatabase, $wgDBmwschema;
1189 $q = <<<END
1190 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1191 WHERE pg_class.relnamespace = pg_namespace.oid
1192 AND attrelid=pg_class.oid AND attnum > 0
1193 AND relname=%s AND nspname=%s
1194 END;
1195 $res = $wgDatabase->query( sprintf( $q,
1196 $wgDatabase->addQuotes( $table ),
1197 $wgDatabase->addQuotes( $wgDBmwschema ) ) );
1198 if ( !$res ) {
1199 return null;
1200 }
1201
1202 $cols = array();
1203 while ( $r = $wgDatabase->fetchRow( $res ) ) {
1204 $cols[] = array(
1205 "name" => $r[0],
1206 "ord" => $r[1],
1207 );
1208 }
1209 return $cols;
1210 }
1211
1212 function pg_describe_index( $idx ) {
1213 global $wgDatabase, $wgDBmwschema;
1214
1215 // first fetch the key (which is a list of columns ords) and
1216 // the table the index applies to (an oid)
1217 $q = <<<END
1218 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1219 WHERE nspname=%s
1220 AND pg_class.relnamespace = pg_namespace.oid
1221 AND relname=%s
1222 AND indexrelid=pg_class.oid
1223 END;
1224 $res = $wgDatabase->query( sprintf( $q,
1225 $wgDatabase->addQuotes( $wgDBmwschema ),
1226 $wgDatabase->addQuotes( $idx ) ) );
1227 if ( !$res ) {
1228 return null;
1229 }
1230 if ( !( $r = $wgDatabase->fetchRow( $res ) ) ) {
1231 $wgDatabase->freeResult( $res );
1232 return null;
1233 }
1234
1235 $indkey = $r[0];
1236 $relid = intval( $r[1] );
1237 $indkeys = explode( " ", $indkey );
1238 $wgDatabase->freeResult( $res );
1239
1240 $colnames = array();
1241 foreach ( $indkeys as $rid ) {
1242 $query = <<<END
1243 SELECT attname FROM pg_class, pg_attribute
1244 WHERE attrelid=$relid
1245 AND attnum=%d
1246 AND attrelid=pg_class.oid
1247 END;
1248 $r2 = $wgDatabase->query( sprintf( $query, $rid ) );
1249 if ( !$r2 ) {
1250 return null;
1251 }
1252 if ( !( $row2 = $wgDatabase->fetchRow( $r2 ) ) ) {
1253 $wgDatabase->freeResult( $r2 );
1254 return null;
1255 }
1256 $colnames[] = $row2[0];
1257 $wgDatabase->freeResult( $r2 );
1258 }
1259
1260 return $colnames;
1261 }
1262
1263 function pg_index_exists( $table, $index ) {
1264 global $wgDatabase, $wgDBmwschema;
1265 $exists = $wgDatabase->selectField( "pg_indexes", "indexname",
1266 array( "indexname" => $index,
1267 "tablename" => $table,
1268 "schemaname" => $wgDBmwschema ) );
1269 return $exists === $index;
1270 }
1271
1272 function pg_fkey_deltype( $fkey ) {
1273 global $wgDatabase, $wgDBmwschema;
1274 $q = <<<END
1275 SELECT confdeltype FROM pg_constraint, pg_namespace
1276 WHERE connamespace=pg_namespace.oid
1277 AND nspname=%s
1278 AND conname=%s;
1279 END;
1280 $r = $wgDatabase->query( sprintf( $q,
1281 $wgDatabase->addQuotes( $wgDBmwschema ),
1282 $wgDatabase->addQuotes( $fkey ) ) );
1283 if ( !( $row = $wgDatabase->fetchRow( $r ) ) ) {
1284 return null;
1285 }
1286 return $row[0];
1287 }
1288
1289 function pg_rule_def( $table, $rule ) {
1290 global $wgDatabase, $wgDBmwschema;
1291 $q = <<<END
1292 SELECT definition FROM pg_rules
1293 WHERE schemaname = %s
1294 AND tablename = %s
1295 AND rulename = %s
1296 END;
1297 $r = $wgDatabase->query( sprintf( $q,
1298 $wgDatabase->addQuotes( $wgDBmwschema ),
1299 $wgDatabase->addQuotes( $table ),
1300 $wgDatabase->addQuotes( $rule ) ) );
1301 $row = $wgDatabase->fetchRow( $r );
1302 if ( !$row ) {
1303 return null;
1304 }
1305 $d = $row[0];
1306 $wgDatabase->freeResult( $r );
1307 return $d;
1308 }
1309
1310 function do_postgres_updates() {
1311 global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1312
1313 # # Gather version numbers in case we need them
1314 $version = $wgDatabase->getServerVersion(); # # long string
1315 $numver = $wgDatabase->numeric_version; # # X.Y e.g. 8.3
1316
1317 $wgShowExceptionDetails = 1;
1318
1319 # Just in case their LocalSettings.php does not have this:
1320 if ( !isset( $wgDBmwschema ) ) {
1321 $wgDBmwschema = 'mediawiki';
1322 }
1323
1324 # Verify that this user is configured correctly
1325 $safeuser = $wgDatabase->addQuotes( $wgDBuser );
1326 $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_catalog.pg_user WHERE usename = $safeuser";
1327 $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1328 $conf = array();
1329 foreach ( explode( '*', $config ) as $c ) {
1330 list( $x, $y ) = explode( '=', $c );
1331 $conf[$x] = $y;
1332 }
1333 if ( !array_key_exists( 'search_path', $conf ) ) {
1334 $search_path = '';
1335 } else {
1336 $search_path = $conf['search_path'];
1337 }
1338 if ( strpos( $search_path, $wgDBmwschema ) === false ) {
1339 wfOut( "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n" );
1340 $search_path = "$wgDBmwschema, $search_path";
1341 }
1342 if ( strpos( $search_path, $wgDBts2schema ) === false ) {
1343 wfOut( "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n" );
1344 $search_path = "$search_path, $wgDBts2schema";
1345 }
1346 $search_path = str_replace( ', ,', ',', $search_path );
1347 if ( array_key_exists( 'search_path', $conf ) === false || $search_path != $conf['search_path'] ) {
1348 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $search_path" );
1349 $wgDatabase->doQuery( "SET search_path = $search_path" );
1350 } else {
1351 $path = $conf['search_path'];
1352 wfOut( "... search_path for user \"$wgDBuser\" looks correct ($path)\n" );
1353 }
1354 $goodconf = array(
1355 'client_min_messages' => 'error',
1356 'DateStyle' => 'ISO, YMD',
1357 'TimeZone' => 'GMT'
1358 );
1359 foreach ( array_keys( $goodconf ) AS $key ) {
1360 $value = $goodconf[$key];
1361 if ( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1362 wfOut( "Setting $key to '$value' for user \"$wgDBuser\"\n" );
1363 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1364 $wgDatabase->doQuery( "SET $key = '$value'" );
1365 } else {
1366 wfOut( "... default value of \"$key\" is correctly set to \"$value\" for user \"$wgDBuser\"\n" );
1367 }
1368 }
1369
1370 $newsequences = array(
1371 "logging_log_id_seq",
1372 "page_restrictions_pr_id_seq",
1373 );
1374
1375 $newtables = array(
1376 array( "category", "patch-category.sql" ),
1377 array( "mwuser", "patch-mwuser.sql" ),
1378 array( "pagecontent", "patch-pagecontent.sql" ),
1379 array( "querycachetwo", "patch-querycachetwo.sql" ),
1380 array( "page_props", "patch-page_props.sql" ),
1381 array( "page_restrictions", "patch-page_restrictions.sql" ),
1382 array( "profiling", "patch-profiling.sql" ),
1383 array( "protected_titles", "patch-protected_titles.sql" ),
1384 array( "redirect", "patch-redirect.sql" ),
1385 array( "updatelog", "patch-updatelog.sql" ),
1386 array( 'change_tag', 'patch-change_tag.sql' ),
1387 array( 'tag_summary', 'patch-change_tag.sql' ),
1388 array( 'valid_tag', 'patch-change_tag.sql' ),
1389 array( 'user_properties', 'patch-user_properties.sql' ),
1390 array( 'log_search', 'patch-log_search.sql' ),
1391 array( 'l10n_cache', 'patch-l10n_cache.sql' ),
1392 array( 'iwlinks', 'patch-iwlinks.sql' ),
1393 );
1394
1395 $newcols = array(
1396 array( "archive", "ar_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
1397 array( "archive", "ar_len", "INTEGER" ),
1398 array( "archive", "ar_page_id", "INTEGER" ),
1399 array( "archive", "ar_parent_id", "INTEGER" ),
1400 array( "image", "img_sha1", "TEXT NOT NULL DEFAULT ''" ),
1401 array( "ipblocks", "ipb_allow_usertalk", "SMALLINT NOT NULL DEFAULT 0" ),
1402 array( "ipblocks", "ipb_anon_only", "SMALLINT NOT NULL DEFAULT 0" ),
1403 array( "ipblocks", "ipb_by_text", "TEXT NOT NULL DEFAULT ''" ),
1404 array( "ipblocks", "ipb_block_email", "SMALLINT NOT NULL DEFAULT 0" ),
1405 array( "ipblocks", "ipb_create_account", "SMALLINT NOT NULL DEFAULT 1" ),
1406 array( "ipblocks", "ipb_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
1407 array( "ipblocks", "ipb_enable_autoblock", "SMALLINT NOT NULL DEFAULT 1" ),
1408 array( "filearchive", "fa_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
1409 array( "logging", "log_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
1410 array( "logging", "log_id", "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('logging_log_id_seq')" ),
1411 array( "logging", "log_params", "TEXT" ),
1412 array( "mwuser", "user_editcount", "INTEGER" ),
1413 array( "mwuser", "user_hidden", "SMALLINT NOT NULL DEFAULT 0" ),
1414 array( "mwuser", "user_newpass_time", "TIMESTAMPTZ" ),
1415 array( "oldimage", "oi_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
1416 array( "oldimage", "oi_major_mime", "TEXT NOT NULL DEFAULT 'unknown'" ),
1417 array( "oldimage", "oi_media_type", "TEXT" ),
1418 array( "oldimage", "oi_metadata", "BYTEA NOT NULL DEFAULT ''" ),
1419 array( "oldimage", "oi_minor_mime", "TEXT NOT NULL DEFAULT 'unknown'" ),
1420 array( "oldimage", "oi_sha1", "TEXT NOT NULL DEFAULT ''" ),
1421 array( "page_restrictions", "pr_id", "INTEGER NOT NULL UNIQUE DEFAULT nextval('page_restrictions_pr_id_val')" ),
1422 array( "profiling", "pf_memory", "NUMERIC(18,10) NOT NULL DEFAULT 0" ),
1423 array( "recentchanges", "rc_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
1424 array( "recentchanges", "rc_log_action", "TEXT" ),
1425 array( "recentchanges", "rc_log_type", "TEXT" ),
1426 array( "recentchanges", "rc_logid", "INTEGER NOT NULL DEFAULT 0" ),
1427 array( "recentchanges", "rc_new_len", "INTEGER" ),
1428 array( "recentchanges", "rc_old_len", "INTEGER" ),
1429 array( "recentchanges", "rc_params", "TEXT" ),
1430 array( "redirect", "rd_interwiki", "TEXT NULL" ),
1431 array( "redirect", "rd_fragment", "TEXT NULL" ),
1432 array( "revision", "rev_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
1433 array( "revision", "rev_len", "INTEGER" ),
1434 array( "revision", "rev_parent_id", "INTEGER DEFAULT NULL" ),
1435 array( "site_stats", "ss_active_users", "INTEGER DEFAULT '-1'" ),
1436 array( "user_newtalk", "user_last_timestamp", "TIMESTAMPTZ" ),
1437 array( "logging", "log_user_text", "TEXT NOT NULL DEFAULT ''" ),
1438 array( "logging", "log_page", "INTEGER" ),
1439 array( "interwiki", "iw_api", "TEXT NOT NULL DEFAULT ''"),
1440 array( "interwiki", "iw_wikiid", "TEXT NOT NULL DEFAULT ''"),
1441 );
1442
1443
1444 # table, column, desired type, USING clause if needed (with new default if needed)
1445 $typechanges = array(
1446 array( "archive", "ar_deleted", "smallint", "" ),
1447 array( "archive", "ar_minor_edit", "smallint", "ar_minor_edit::smallint DEFAULT 0" ),
1448 array( "filearchive", "fa_deleted", "smallint", "" ),
1449 array( "filearchive", "fa_height", "integer", "" ),
1450 array( "filearchive", "fa_metadata", "bytea", "decode(fa_metadata,'escape')" ),
1451 array( "filearchive", "fa_size", "integer", "" ),
1452 array( "filearchive", "fa_width", "integer", "" ),
1453 array( "filearchive", "fa_storage_group", "text", "" ),
1454 array( "filearchive", "fa_storage_key", "text", "" ),
1455 array( "image", "img_metadata", "bytea", "decode(img_metadata,'escape')" ),
1456 array( "image", "img_size", "integer", "" ),
1457 array( "image", "img_width", "integer", "" ),
1458 array( "image", "img_height", "integer", "" ),
1459 array( "interwiki", "iw_local", "smallint", "iw_local::smallint DEFAULT 0" ),
1460 array( "interwiki", "iw_trans", "smallint", "iw_trans::smallint DEFAULT 0" ),
1461 array( "ipblocks", "ipb_auto", "smallint", "ipb_auto::smallint DEFAULT 0" ),
1462 array( "ipblocks", "ipb_anon_only", "smallint", "CASE WHEN ipb_anon_only=' ' THEN 0 ELSE ipb_anon_only::smallint END DEFAULT 0" ),
1463 array( "ipblocks", "ipb_create_account", "smallint", "CASE WHEN ipb_create_account=' ' THEN 0 ELSE ipb_create_account::smallint END DEFAULT 1" ),
1464 array( "ipblocks", "ipb_enable_autoblock", "smallint", "CASE WHEN ipb_enable_autoblock=' ' THEN 0 ELSE ipb_enable_autoblock::smallint END DEFAULT 1" ),
1465 array( "ipblocks", "ipb_block_email", "smallint", "CASE WHEN ipb_block_email=' ' THEN 0 ELSE ipb_block_email::smallint END DEFAULT 0" ),
1466 array( "ipblocks", "ipb_address", "text", "ipb_address::text" ),
1467 array( "ipblocks", "ipb_deleted", "smallint", "ipb_deleted::smallint DEFAULT 0" ),
1468 array( "math", "math_inputhash", "bytea", "decode(math_inputhash,'escape')" ),
1469 array( "math", "math_outputhash", "bytea", "decode(math_outputhash,'escape')" ),
1470 array( "mwuser", "user_token", "text", "" ),
1471 array( "mwuser", "user_email_token", "text", "" ),
1472 array( "objectcache", "keyname", "text", "" ),
1473 array( "oldimage", "oi_height", "integer", "" ),
1474 array( "oldimage", "oi_metadata", "bytea", "decode(img_metadata,'escape')" ),
1475 array( "oldimage", "oi_size", "integer", "" ),
1476 array( "oldimage", "oi_width", "integer", "" ),
1477 array( "page", "page_is_redirect", "smallint", "page_is_redirect::smallint DEFAULT 0" ),
1478 array( "page", "page_is_new", "smallint", "page_is_new::smallint DEFAULT 0" ),
1479 array( "querycache", "qc_value", "integer", "" ),
1480 array( "querycachetwo", "qcc_value", "integer", "" ),
1481 array( "recentchanges", "rc_bot", "smallint", "rc_bot::smallint DEFAULT 0" ),
1482 array( "recentchanges", "rc_deleted", "smallint", "" ),
1483 array( "recentchanges", "rc_minor", "smallint", "rc_minor::smallint DEFAULT 0" ),
1484 array( "recentchanges", "rc_new", "smallint", "rc_new::smallint DEFAULT 0" ),
1485 array( "recentchanges", "rc_type", "smallint", "rc_type::smallint DEFAULT 0" ),
1486 array( "recentchanges", "rc_patrolled", "smallint", "rc_patrolled::smallint DEFAULT 0" ),
1487 array( "revision", "rev_deleted", "smallint", "rev_deleted::smallint DEFAULT 0" ),
1488 array( "revision", "rev_minor_edit", "smallint", "rev_minor_edit::smallint DEFAULT 0" ),
1489 array( "templatelinks", "tl_namespace", "smallint", "tl_namespace::smallint" ),
1490 array( "user_newtalk", "user_ip", "text", "host(user_ip)" ),
1491 );
1492
1493 # table, column, nullability
1494 $nullchanges = array(
1495 array( "oldimage", "oi_bits", "NULL" ),
1496 array( "oldimage", "oi_timestamp", "NULL" ),
1497 array( "oldimage", "oi_major_mime", "NULL" ),
1498 array( "oldimage", "oi_minor_mime", "NULL" ),
1499 );
1500
1501 $newindexes = array(
1502 array( "archive", "archive_user_text", "(ar_user_text)" ),
1503 array( "image", "img_sha1", "(img_sha1)" ),
1504 array( "oldimage", "oi_sha1", "(oi_sha1)" ),
1505 array( "revision", "rev_text_id_idx", "(rev_text_id)" ),
1506 array( "recentchanges", "rc_timestamp_bot", "(rc_timestamp) WHERE rc_bot = 0" ),
1507 array( "templatelinks", "templatelinks_from", "(tl_from)" ),
1508 array( "watchlist", "wl_user", "(wl_user)" ),
1509 array( "logging", "logging_user_type_time", "(log_user, log_type, log_timestamp)" ),
1510 array( "logging", "logging_page_id_time", "(log_page,log_timestamp)" ),
1511 );
1512
1513 $newrules = array(
1514 );
1515
1516 # # All FK columns should be deferred
1517 $deferredcols = array(
1518 array( "archive", "ar_user", "mwuser(user_id) ON DELETE SET NULL" ),
1519 array( "categorylinks", "cl_from", "page(page_id) ON DELETE CASCADE" ),
1520 array( "externallinks", "el_from", "page(page_id) ON DELETE CASCADE" ),
1521 array( "filearchive", "fa_deleted_user", "mwuser(user_id) ON DELETE SET NULL" ),
1522 array( "filearchive", "fa_user", "mwuser(user_id) ON DELETE SET NULL" ),
1523 array( "image", "img_user", "mwuser(user_id) ON DELETE SET NULL" ),
1524 array( "imagelinks", "il_from", "page(page_id) ON DELETE CASCADE" ),
1525 array( "ipblocks", "ipb_by", "mwuser(user_id) ON DELETE CASCADE" ),
1526 array( "ipblocks", "ipb_user", "mwuser(user_id) ON DELETE SET NULL" ),
1527 array( "langlinks", "ll_from", "page(page_id) ON DELETE CASCADE" ),
1528 array( "logging", "log_user", "mwuser(user_id) ON DELETE SET NULL" ),
1529 array( "oldimage", "oi_name", "image(img_name) ON DELETE CASCADE ON UPDATE CASCADE" ),
1530 array( "oldimage", "oi_user", "mwuser(user_id) ON DELETE SET NULL" ),
1531 array( "pagelinks", "pl_from", "page(page_id) ON DELETE CASCADE" ),
1532 array( "page_props", "pp_page", "page (page_id) ON DELETE CASCADE" ),
1533 array( "page_restrictions", "pr_page", "page(page_id) ON DELETE CASCADE" ),
1534 array( "protected_titles", "pt_user", "mwuser(user_id) ON DELETE SET NULL" ),
1535 array( "recentchanges", "rc_cur_id", "page(page_id) ON DELETE SET NULL" ),
1536 array( "recentchanges", "rc_user", "mwuser(user_id) ON DELETE SET NULL" ),
1537 array( "redirect", "rd_from", "page(page_id) ON DELETE CASCADE" ),
1538 array( "revision", "rev_page", "page (page_id) ON DELETE CASCADE" ),
1539 array( "revision", "rev_user", "mwuser(user_id) ON DELETE RESTRICT" ),
1540 array( "templatelinks", "tl_from", "page(page_id) ON DELETE CASCADE" ),
1541 array( "trackbacks", "tb_page", "page(page_id) ON DELETE CASCADE" ),
1542 array( "user_groups", "ug_user", "mwuser(user_id) ON DELETE CASCADE" ),
1543 array( "user_newtalk", "user_id", "mwuser(user_id) ON DELETE CASCADE" ),
1544 array( "user_properties", "up_user", "mwuser(user_id) ON DELETE CASCADE" ),
1545 array( "watchlist", "wl_user", "mwuser(user_id) ON DELETE CASCADE" ),
1546 );
1547
1548 # Check new sequences, rename if needed
1549 foreach ( $newsequences as $ns ) {
1550 if ( $wgDatabase->sequenceExists( 'pr_id_val' ) ) {
1551 wfOut( "Updating sequence names\n" );
1552 $wgDatabase->sourceFile( archive( 'patch-update_sequences.sql' ) );
1553 continue;
1554 } elseif ( $wgDatabase->sequenceExists( 'page_restrictions_pr_id_seq' ) ) {
1555 wfOut( "... sequences already updated\n" );
1556 continue;
1557 } else {
1558 wfOut( "Creating sequence \"$ns\"\n" );
1559 $wgDatabase->query( "CREATE SEQUENCE $ns" );
1560 }
1561 }
1562
1563 foreach ( $newtables as $nt ) {
1564 if ( $wgDatabase->tableExists( $nt[0] ) ) {
1565 wfOut( "... table \"$nt[0]\" already exists\n" );
1566 continue;
1567 }
1568
1569 wfOut( "Creating table \"$nt[0]\"\n" );
1570 $wgDatabase->sourceFile( archive( $nt[1] ) );
1571 }
1572
1573 # # Needed before newcols
1574 if ( $wgDatabase->tableExists( "archive2" ) ) {
1575 wfOut( "Converting \"archive2\" back to normal archive table\n" );
1576 if ( $wgDatabase->ruleExists( "archive", "archive_insert" ) ) {
1577 wfOut( "Dropping rule \"archive_insert\"\n" );
1578 $wgDatabase->query( "DROP RULE archive_insert ON archive" );
1579 }
1580 if ( $wgDatabase->ruleExists( "archive", "archive_delete" ) ) {
1581 wfOut( "Dropping rule \"archive_delete\"\n" );
1582 $wgDatabase->query( "DROP RULE archive_delete ON archive" );
1583 }
1584 $wgDatabase->sourceFile( archive( "patch-remove-archive2.sql" ) );
1585 }
1586 else
1587 wfOut( "... obsolete table \"archive2\" does not exist\n" );
1588
1589 foreach ( $newcols as $nc ) {
1590 $fi = $wgDatabase->fieldInfo( $nc[0], $nc[1] );
1591 if ( !is_null( $fi ) ) {
1592 wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
1593 continue;
1594 }
1595
1596 wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
1597 $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
1598 }
1599
1600 foreach ( $typechanges as $tc ) {
1601 $fi = $wgDatabase->fieldInfo( $tc[0], $tc[1] );
1602 if ( is_null( $fi ) ) {
1603 wfOut( "... error: expected column $tc[0].$tc[1] to exist\n" );
1604 exit( 1 );
1605 }
1606
1607 if ( $fi->type() === $tc[2] )
1608 wfOut( "... column \"$tc[0].$tc[1]\" is already of type \"$tc[2]\"\n" );
1609 else {
1610 wfOut( "Changing column type of \"$tc[0].$tc[1]\" from \"{$fi->type()}\" to \"$tc[2]\"\n" );
1611 $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1612 if ( strlen( $tc[3] ) ) {
1613 $default = array();
1614 if ( preg_match( '/DEFAULT (.+)/', $tc[3], $default ) ) {
1615 $sqldef = "ALTER TABLE $tc[0] ALTER $tc[1] SET DEFAULT $default[1]";
1616 $wgDatabase->query( $sqldef );
1617 $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3] );
1618 }
1619 $sql .= " USING $tc[3]";
1620 }
1621 $sql .= ";\nCOMMIT;\n";
1622 $wgDatabase->query( $sql );
1623 }
1624 }
1625
1626 foreach ( $nullchanges as $nc ) {
1627 $fi = $wgDatabase->fieldInfo( $nc[0], $nc[1] );
1628 if ( is_null( $fi ) ) {
1629 wfOut( "... error: expected column $nc[0].$nc[1] to exist\n" );
1630 exit( 1 );
1631 }
1632 if ( $fi->nullable() ) {
1633 # # It's NULL - does it need to be NOT NULL?
1634 if ( 'NOT NULL' === $nc[2] ) {
1635 wfOut( "Changing \"$nc[0].$nc[1]\" to not allow NULLs\n" );
1636 $wgDatabase->query( "ALTER TABLE $nc[0] ALTER $nc[1] SET NOT NULL" );
1637 } else {
1638 wfOut( "... column \"$nc[0].$nc[1]\" is already set as NULL\n" );
1639 }
1640 } else {
1641 # # It's NOT NULL - does it need to be NULL?
1642 if ( 'NULL' === $nc[2] ) {
1643 wfOut( "Changing \"$nc[0].$nc[1]\" to allow NULLs\n" );
1644 $wgDatabase->query( "ALTER TABLE $nc[0] ALTER $nc[1] DROP NOT NULL" );
1645 }
1646 else {
1647 wfOut( "... column \"$nc[0].$nc[1]\" is already set as NOT NULL\n" );
1648 }
1649 }
1650 }
1651
1652 if ( $wgDatabase->fieldInfo( 'oldimage', 'oi_deleted' )->type() !== 'smallint' ) {
1653 wfOut( "Changing \"oldimage.oi_deleted\" to type \"smallint\"\n" );
1654 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted DROP DEFAULT" );
1655 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted TYPE SMALLINT USING (oi_deleted::smallint)" );
1656 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted SET DEFAULT 0" );
1657 } else {
1658 wfOut( "... column \"oldimage.oi_deleted\" is already of type \"smallint\"\n" );
1659 }
1660
1661 foreach ( $newindexes as $ni ) {
1662 if ( pg_index_exists( $ni[0], $ni[1] ) ) {
1663 wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
1664 continue;
1665 }
1666 wfOut( "Creating index \"$ni[1]\" on table \"$ni[0]\" $ni[2]\n" );
1667 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1668 }
1669
1670 foreach ( $newrules as $nr ) {
1671 if ( $wgDatabase->ruleExists( $nr[0], $nr[1] ) ) {
1672 wfOut( "... rule \"$nr[1]\" on table \"$nr[0]\" already exists\n" );
1673 continue;
1674 }
1675 wfOut( "Adding rule \"$nr[1]\" to table \"$nr[0]\"\n" );
1676 $wgDatabase->sourceFile( archive( $nr[2] ) );
1677 }
1678
1679 if ( $wgDatabase->hasConstraint( "oldimage_oi_name_fkey_cascaded" ) ) {
1680 wfOut( "... table \"oldimage\" has correct cascading delete/update foreign key to image\n" );
1681 } else {
1682 if ( $wgDatabase->hasConstraint( "oldimage_oi_name_fkey" ) ) {
1683 $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey" );
1684 }
1685 if ( $wgDatabase->hasConstraint( "oldimage_oi_name_fkey_cascade" ) ) {
1686 $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey_cascade" );
1687 }
1688 wfOut( "Making foreign key on table \"oldimage\" (to image) a cascade delete/update\n" );
1689 $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascaded " .
1690 "FOREIGN KEY (oi_name) REFERENCES image(img_name) ON DELETE CASCADE ON UPDATE CASCADE" );
1691 }
1692
1693 if ( !$wgDatabase->triggerExists( "page", "page_deleted" ) ) {
1694 wfOut( "Adding function and trigger \"page_deleted\" to table \"page\"\n" );
1695 $wgDatabase->sourceFile( archive( 'patch-page_deleted.sql' ) );
1696 } else {
1697 wfOut( "... table \"page\" has \"page_deleted\" trigger\n" );
1698 }
1699
1700 $fi = $wgDatabase->fieldInfo( "recentchanges", "rc_cur_id" );
1701 if ( !$fi->nullable() ) {
1702 wfOut( "Removing NOT NULL constraint from \"recentchanges.rc_cur_id\"\n" );
1703 $wgDatabase->sourceFile( archive( 'patch-rc_cur_id-not-null.sql' ) );
1704 } else {
1705 wfOut( "... column \"recentchanges.rc_cur_id\" has a NOT NULL constraint\n" );
1706 }
1707
1708 $pu = pg_describe_index( "pagelink_unique" );
1709 if ( !is_null( $pu ) && ( $pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title" ) ) {
1710 wfOut( "Dropping obsolete version of index \"pagelink_unique index\"\n" );
1711 $wgDatabase->query( "DROP INDEX pagelink_unique" );
1712 $pu = null;
1713 } else {
1714 wfOut( "... obsolete version of index \"pagelink_unique index\" does not exist\n" );
1715 }
1716
1717 if ( is_null( $pu ) ) {
1718 wfOut( "Creating index \"pagelink_unique index\"\n" );
1719 $wgDatabase->query( "CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)" );
1720 } else {
1721 wfOut( "... index \"pagelink_unique_index\" already exists\n" );
1722 }
1723
1724 if ( pg_fkey_deltype( "revision_rev_user_fkey" ) == 'r' ) {
1725 wfOut( "... constraint \"revision_rev_user_fkey\" is ON DELETE RESTRICT\n" );
1726 } else {
1727 wfOut( "Changing constraint \"revision_rev_user_fkey\" to ON DELETE RESTRICT\n" );
1728 $wgDatabase->sourceFile( archive( 'patch-revision_rev_user_fkey.sql' ) );
1729 }
1730
1731 # Fix ipb_address index
1732 if ( pg_index_exists( 'ipblocks', 'ipb_address' ) ) {
1733 wfOut( "Removing deprecated index 'ipb_address'...\n" );
1734 $wgDatabase->query( 'DROP INDEX ipb_address' );
1735 }
1736 if ( pg_index_exists( 'ipblocks', 'ipb_address_unique' ) ) {
1737 wfOut( "... have ipb_address_unique\n" );
1738 } else {
1739 wfOut( "Adding ipb_address_unique index\n" );
1740 $wgDatabase->sourceFile( archive( 'patch-ipb_address_unique.sql' ) );
1741 }
1742
1743 # Fix iwlinks index
1744 if ( pg_index_exists( 'iwlinks', 'iwl_prefix' ) ) {
1745 wfOut( "Replacing index 'iwl_prefix' with 'iwl_prefix_from_title'...\n" );
1746 $wgDatabase->sourceFile( archive( 'patch-rename-iwl_prefix.sql' ) );
1747 }
1748
1749 global $wgExtNewTables, $wgExtPGNewFields, $wgExtPGAlteredFields, $wgExtNewIndexes;
1750 # Add missing extension tables
1751 foreach ( $wgExtNewTables as $nt ) {
1752 if ( $wgDatabase->tableExists( $nt[0] ) ) {
1753 wfOut( "... table \"$nt[0]\" already exists\n" );
1754 continue;
1755 }
1756 wfOut( "Creating table \"$nt[0]\"\n" );
1757 $wgDatabase->sourceFile( $nt[1] );
1758 }
1759 # Add missing extension fields
1760 foreach ( $wgExtPGNewFields as $nc ) {
1761 $fi = $wgDatabase->fieldInfo( $nc[0], $nc[1] );
1762 if ( !is_null( $fi ) ) {
1763 wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
1764 continue;
1765 }
1766 wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
1767 $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
1768 }
1769 # Change altered columns
1770 foreach ( $wgExtPGAlteredFields as $nc ) {
1771 $fi = $wgDatabase->fieldInfo( $nc[0], $nc[1] );
1772 if ( is_null( $fi ) ) {
1773 wfOut( "WARNING! Column \"$nc[0].$nc[1]\" does not exist but had an alter request! Please report this.\n" );
1774 continue;
1775 }
1776 $oldtype = $fi->type();
1777 $newtype = strtolower( $nc[2] );
1778 if ( $oldtype === $newtype ) {
1779 wfOut( "... column \"$nc[0].$nc[1]\" has correct type of \"$newtype\"\n" );
1780 continue;
1781 }
1782 $command = "ALTER TABLE $nc[0] ALTER $nc[1] TYPE $nc[2]";
1783 if ( isset( $nc[3] ) ) {
1784 $command .= " USING $nc[3]";
1785 }
1786 wfOut( "Altering column \"$nc[0].$nc[1]\" from type \"$oldtype\" to \"$newtype\"\n" );
1787 $wgDatabase->query( $command );
1788 }
1789 # Add missing extension indexes
1790 foreach ( $wgExtNewIndexes as $ni ) {
1791 if ( pg_index_exists( $ni[0], $ni[1] ) ) {
1792 wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
1793 continue;
1794 }
1795 wfOut( "Creating index \"$ni[1]\" on table \"$ni[0]\"\n" );
1796 if ( preg_match( '/^\(/', $ni[2] ) ) {
1797 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1798 }
1799 else {
1800 $wgDatabase->sourceFile( $ni[2] );
1801 }
1802 }
1803
1804 foreach ( $deferredcols AS $dc ) {
1805 $fi = $wgDatabase->fieldInfo( $dc[0], $dc[1] );
1806 if ( is_null( $fi ) ) {
1807 wfOut( "WARNING! Column \"$dc[0].$dc[1]\" does not exist but it should! Please report this.\n" );
1808 continue;
1809 }
1810 if ( $fi->is_deferred() && $fi->is_deferrable() ) {
1811 continue;
1812 }
1813 wfOut( "Altering column \"$dc[0].$dc[1]\" to be DEFERRABLE INITIALLY DEFERRED\n" );
1814 $conname = $fi->conname();
1815 $clause = $dc[2];
1816 $command = "ALTER TABLE $dc[0] DROP CONSTRAINT $conname";
1817 $wgDatabase->query( $command );
1818 $command = "ALTER TABLE $dc[0] ADD CONSTRAINT $conname FOREIGN KEY ($dc[1]) REFERENCES $clause DEFERRABLE INITIALLY DEFERRED";
1819 $wgDatabase->query( $command );
1820 }
1821
1822 # Tweak the page_title tsearch2 trigger to filter out slashes
1823 # This is create or replace, so harmless to call if not needed
1824 $wgDatabase->sourceFile( archive( 'patch-ts2pagetitle.sql' ) );
1825
1826 # # If the server is 8.3 or higher, rewrite the tsearch2 triggers
1827 # # in case they have the old 'default' versions
1828 if ( $numver >= 8.3 ) {
1829 $wgDatabase->sourceFile( archive( 'patch-tsearch2funcs.sql' ) );
1830 }
1831 return;
1832 }